<?php

namespace app\admin\controller;

use think\Request;
use think\Db;

class User extends Common 
{
	/**
	 * 用户管理首页
	 */
	public function index()
	{	
		$page      = input('?get.page') ? input('get.page') : 1;
		$pageSize  = 2;
		$totalRows = DB::name('user')->count();
		$totalPage = ceil($totalRows/$pageSize);
		$infoList  = DB::name('user')->field('id, username, email, activeFlag')->page($page, $pageSize)->select();

		$this->assign('page', $page);
		$this->assign('infoList', $infoList);
		$this->assign('pageSize', $pageSize);
		$this->assign('totalPage', $totalPage);

		return $this->fetch();

	}

	/**
	 * 添加用户
	 */
	public function add()
	{	
		if (Request::instance()->isPost()) {
			$username = input('post.username');
			$password = input('post.password');
			$email    = input('post.email');
			$sex      = input('post.sex');

			$validate = Loader::validate('Admin');
			$data     = ['username'=>$username, 'password'=>$password, 'email'=>$email];
			if (!$validate->scene('add')->check($data)) {
                return $this->error($validate->getError());
            }

			$value['username'] = $username;
			$value['password'] = md5($password);
			$value['email']    = $email;
			$value['sex']      = $sex;
			$value['regTime']  = time();

	  		$id = Db::name('user')->insertGetId($value);

	  		if($id) {
	  			return $this->success('操作成功','/admin/admin/index');
	  		} else {
	  			return $this->error('操作失败');
	  		}	
		} else {
			return $this->fetch();
		}
		
	}

	/**
	 * 删除用户
	 */
	public function delete()
	{	
		$id = input('get.id');
		$num = DB::name('user')->where('id', $id)->delete();
		if ($num) {
			return $this->success('删除成功', '/admin/admin/index');
		}else{
			return $this->error('删除失败');
		}
	}

	/**
	 * 编辑用户
	 */
	public function edit()
	{
		if (Request::instance()->isPost()) {
			$id   = input('get.id');
			$data = array();
			$username = input('post.username');
			$password = input('post.password');
			$email    = input('post.email');
			$sex      = input('sex');

			$data['username'] = $username;
			$oldPassword = DB::name('admin')->where('id', $id)->value('password');
			if ($oldPassword != $password && $password != null) {
				$data['password'] = md5($password);
			}

			if ($email != NULL) {
				$data['email']    = $email;
			}

			$num = DB::name('admin')->where('id', $id)->update($data);
			if ($num) {
				return $this->success('更新成功', '/admin/admin/index');
			}else{
				return $this->error('更新失败');
			}
		}else{
			$id = input('get.id');
			$info = DB::name('user')->field('username, password, email, sex')->where('id', $id)->find();
			$this->assign('id', $id);
			$this->assign('info',$info);
			return $this->fetch();
		}
	}	
}
